<template>
  <div>
    <h2>表位检测结果</h2>
    <!-- 动态生成多个表格，每个表格显示不同的数据 -->
    <div style="margin:5%" v-for="(table, index) in tables" :key="index">
      <h3>{{ table.name }}</h3>
      <el-table :data="table.data" style="width: 100%" :height="getTableHeight(table.data)">
        <el-table-column
          v-for="key in table.headers"
          :prop="key"
          :key="key"
          :label="key"
          :width="120"
        />
      </el-table>
    </div>
    <div style="height:80px"></div>

    <!-- 固定在右下角的文件上传输入框和按钮 -->
    <div class="fixed-bottom-right">
      <input type="file" style="width: 100px" @change="handleFileUpload($event.target.files[0])" accept=".csv" />
      <span style="margin: 5px"/>
      <div v-if="csvData.length > 0">
        <button @click="uploadData">上传到后端</button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import useCsvReader from "../../utils/useCsvReader";
import { createEpitopeResult, selectEpitopeResultByPatientId } from "../../api/epitopeResults";
import { useRoute } from "vue-router";

const route = useRoute();
const { csvFileName, csvHeaders, csvData, csvFileSize, handleFileUpload } = useCsvReader();

const tables = ref([]);

const uploadData = async () => {
  const epitopeResult = {
    patientId: +route.params.patientId,
    fileName: csvFileName.value,
    filePath: '/lsdjf/sdf/wen.csv', // Adjust filePath as needed
    fileHeader: JSON.stringify(csvHeaders.value),
    fileContent: JSON.stringify(csvData.value),
    fileSize: csvFileSize.value,
  };

  try {
    const response = await createEpitopeResult(epitopeResult);
    console.log(response.data, '数据上传成功');
  } catch (error) {
    console.error('Error uploading data:', error);
  }
};

const getTestResultByPatientId = async () => {
  try {
    const response = await selectEpitopeResultByPatientId(+route.params.patientId);
    tables.value = response.data.map((table, index) => ({
      name: `表格 ${index + 1}`,
      headers: JSON.parse(table.fileHeader),
      data: JSON.parse(table.fileContent),
    }));
  } catch (error) {
    console.error('Error fetching data:', error);
  }
};

const getTableHeight = (data: any) => {
  const rowHeight = 70; // 每行的高度
  const maxTableHeight = 500; // 表格的最大高度
  const tableHeight = data.length * rowHeight;
  return tableHeight > maxTableHeight ? maxTableHeight : tableHeight;
};

onMounted(async () => {
  await getTestResultByPatientId();
});


</script>

<style scoped>
.fixed-bottom-right {
  position: fixed;
  bottom: 10px;
  right: 10px;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}
</style>
